using System.Collections;
using System.Collections.Generic;
using System.Html;
using System.Runtime.CompilerServices;
using Awaiter;
using Nsb.Classes;
using ThemeChain;
using jQueryApi;

namespace Yoshi.Classes
{
    [IgnoreNamespace]
    public class ImageManager : FileBlobBase
    {
        public static void ThumbToFullAw(Await awp, string url)
        {
            //Dictionary<string, ImageItem> imgs = new Dictionary();
            awp.Result = url;
            new Await()
                .AddAw(RetrieveBlobAw, ThemeYoshi.ImagesPartitionKey, ThemeYoshi.ImagesRowKey)
                .HandleDl(Exceptions.BlobLoadError, Await.FinishAw)
                //.SetResult(new List<object>(imgs), Exceptions.BlobLoadError)
                .AddDx(
                    delegate(Await aw)
                    {
                        Dictionary<string, ImageItem> imgs = (Dictionary)aw.Result ?? new Dictionary();
                        foreach (KeyValuePair<string, ImageItem> p in imgs)
                        {
                            if (p.Value.Thumb != url) continue;
                            awp.Result = p.Value.Path ?? p.Value.Source;
                            return;
                        }
                    })
                .Commit(awp);
        }

        public static void UpdateImageDataAw(Await awp, string url)
        {
            jQueryObject ix = null;
            new Await()
                .AddDx(delegate { ix = jQuery.FromHtml("<img style='position:absolute;top:-50000px;'/>").Attribute("src", url).AppendTo(Document.Body); })
                .WaitDx(delegate { return ix.GetHeight() > 0; })
                .AddAw(FileManager.UpdateFileAw, ThemeYoshi.ImagesPartitionKey, ThemeYoshi.ImagesRowKey,
                       delegate(object imagesD, object[] imagesO)
                       {
                           imagesD = imagesD ?? new Dictionary();
                           imagesO[0] = imagesD; // Tell the callback we could have changed the dictionary
                           Dictionary<string, ImageItem> images = (Dictionary) imagesD;
                           string lurl = ThemeYoshi.LocalUrl(url);
                           string id = lurl ?? url;
                           ImageItem imi = images[id] ?? new ImageItem();
                           //imi.Thumb = null;
                           if (lurl != null)
                           {
                               imi.Path = lurl;
                               imi.Master = lurl;
                               imi.Source = lurl;
                               imi.Thumb = imi.Thumb ?? CreateThumbnail(lurl.Substr(ThemeBase.AppUri.Length + 1));
                           }
                           else
                           {
                               imi.Source = url;
                               imi.Thumb = imi.Thumb ?? CreateThumbnail(url);
                           }
                           imi.Width = ix.GetWidth();
                           imi.Height = ix.GetHeight();
                           images[id] = imi;
                           ix.Remove();
                       }
                )
                .Commit(awp);
        }

        public static void ClearThumbsAw(Await awp)
        {
            new Await()
                .AddAw(FileManager.UpdateFileAw, ThemeYoshi.ImagesPartitionKey, ThemeYoshi.ImagesRowKey,
                       delegate(object imagesD, object[] imagesO)
                       {
                           imagesD = imagesD ?? new Dictionary();
                           imagesO[0] = imagesD; // Tell the callback we could have changed the dictionary
                           Dictionary<string, ImageItem> images = (Dictionary) imagesD;
                           foreach (KeyValuePair<string, ImageItem> p in images)
                           {
                               if (p.Value.Thumb != null)
                               {
                                   DeleteImageAw(Await.AsyncAw, p.Value.Thumb);
                                   p.Value.Thumb = null;
                               }
                           }
                       }
                )
                .Commit(awp);
        }

        public static void DeleteImageAw(Await awp, string url)
        {
            DeleteItemAw(awp, Uri.Front(url).Substr(ThemeBase.AppUri.Length + 1), Uri.End(url));
        }

        /// <summary>
        /// Creates the thumbnail image on the server.
        /// </summary>
        /// <param name="url">The URL or file path</param>
        /// <returns>the full server based uri of the created thumbnail</returns>
        public static string CreateThumbnail(string url)
        {
            string en = Uri.End(url);
            string name = Uri.Join("pg/images", "tn." + (Uri.IsHttp(url) ? Formulas.NewId + Uri.Ext(en) : en));

            jQueryAjaxOptions options = new jQueryAjaxOptions();
            options.Url = Uri.Join(ThemeBase.AppUri, "file.thumbnail.php");
            options.DataType = "json";
            options.Type = "GET";
            options.Data = new Dictionary(
                "source", url,
                "file", name,
                "width", 100,
                "password", Password
                );

            options.Success =
                delegate { };

            options.Error =
                delegate { };
            jQuery.Ajax(options);
            return Uri.Join(ThemeBase.AppUri, name);
        }
    }
}